package thread;

/**
 * 哲学家吃饭问题
 */
class Fork{
    private boolean[] used = {false,false,false,false,false};

    public synchronized  void takeFork(){
        String name = Thread.currentThread().getName();
        int i = Integer.parseInt(name);
        while(used[i]||used[(i+1)%5]){
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        used[i] = true;
        used[(i+1)%5] = true;
    }
    public synchronized void putFork(){
        String name = Thread.currentThread().getName();
        int i =Integer.parseInt(name);
        used[i] = false;
        used[(i+1)%5] = false;
        notifyAll();
    }
}

public class ThreadDemo15 extends Thread{
    private String name;
    private Fork fork;

    public ThreadDemo15(String name, Fork fork) {
        super(name);
        this.name = name;
        this.fork = fork;
    }
    public void thinking(){
        System.out.println("小朋友"+name+"在玩游戏");
        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void eating(){
        System.out.println("小朋友"+name+"正在吃饭");
        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while(true){
            thinking();
            fork.takeFork();
            eating();
            fork.putFork();
        }
    }
    public static void main(String[] args) {
        Fork fork1 = new Fork();

        new ThreadDemo15("0",fork1).start();
        new ThreadDemo15("1",fork1).start();
        new ThreadDemo15("2",fork1).start();
        new ThreadDemo15("3",fork1).start();
        new ThreadDemo15("4",fork1).start();
    }
}